package com.my.swas.sso.common.shiro;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.support.DisabledSessionException;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Description:
 * @author: :MaYong
 */
public class MyShiroHttpServletRequest extends ShiroHttpServletRequest {

    public MyShiroHttpServletRequest(HttpServletRequest wrapped, ServletContext servletContext, boolean httpSessions) {
        super(wrapped, servletContext, httpSessions);
    }
    @Override
    public HttpSession getSession() {
        return this.getSession(true);
    }

    @Override
    public HttpSession getSession(boolean create) {
        HttpSession httpSession;

        if(this.isHttpSessions()) {
            httpSession = super.getSession(false);
            if(httpSession == null && create) {
                if(!WebUtils._isSessionCreationEnabled(this)) {
                    throw this.newNoSessionCreationException();
                }
                httpSession = super.getSession(create);
            }
        } else {
            if(this.session == null) {
                try {
                    boolean existing = this.getSubject().getSession(false) != null;
                    Session shiroSession = this.getSubject().getSession(create);
                    if(shiroSession != null) {
                        this.session = new ShiroHttpSession(shiroSession, this, this.servletContext);
                        if(!existing) {
                            this.setAttribute(REFERENCED_SESSION_IS_NEW, Boolean.TRUE);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            httpSession = this.session;
        }

        return httpSession;
    }

    private DisabledSessionException newNoSessionCreationException() {
        String msg = "Session creation has been disabled for the current request.  This exception indicates that there is either a programming error (using a session when it should never be used) or that Shiro's configuration needs to be adjusted to allow Sessions to be created for the current request.  See the " + DisabledSessionException.class.getName() + " JavaDoc " + "for more.";
        return new DisabledSessionException(msg);
    }


}
